#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import time
import signal
import subprocess
import platform
import webbrowser
from pathlib import Path

def check_environment():
    """检查运行环境"""
    # 检查Python版本
    if sys.version_info < (3, 7):
        print("错误: 需要Python 3.7或更高版本")
        return False
    
    # 检查Node.js
    try:
        subprocess.run(['npm', '--version'], capture_output=True, check=True)
    except (subprocess.SubprocessError, FileNotFoundError):
        print("错误: 未找到npm，请确保已安装Node.js")
        return False
    
    return True

def start_services():
    """启动前后端服务"""
    # 获取项目根目录
    root_dir = Path(__file__).parent.parent.absolute()
    os.chdir(root_dir)
    
    # 启动后端
    print("正在启动后端服务...")
    backend = subprocess.Popen(
        [sys.executable, 'run.py'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    
    # 等待后端启动
    time.sleep(5)
    
    # 启动前端
    print("正在启动前端服务...")
    frontend_dir = root_dir / 'src' / 'frontend'
    os.chdir(frontend_dir)
    
    frontend = subprocess.Popen(
        ['npm', 'run', 'dev'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    
    return backend, frontend

def main():
    """主函数"""
    print("正在启动应用程序框架分析器...")
    
    if not check_environment():
        sys.exit(1)
    
    try:
        backend, frontend = start_services()
        
        print("\n服务已启动！")
        print("后端API: http://localhost:5000")
        print("前端界面: http://localhost:5173")
        
        # 自动打开浏览器
        webbrowser.open('http://localhost:5173')
        
        # 等待用户按Ctrl+C
        def signal_handler(signum, frame):
            print("\n正在停止服务...")
            backend.terminate()
            frontend.terminate()
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        
        # 保持脚本运行
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        backend.terminate()
        frontend.terminate()
    except Exception as e:
        print(f"发生错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main() 